const mongoose = require("mongoose");

class Db {
	constructor(model) {
		this.model = model;
	}
	_connect(){
		// 判断是否已经连接成功了
		if(mongoose.connection.readyState === 1) return Promise.resolve();
		return mongoose.connect("mongodb://127.0.0.1:27017/hy02",{
			serverSelectionTimeoutMs:10000
		})
	}
	// 插入一条记录
	// insertObj:插入的文档记录
	async insertOne(insertObj){
		await this._connect();
		return this.model(insertObj).save();
	}
	// whereObj:条件
	async count(whereObj){
		await this._connect();
		return this.model.countDocuments(whereObj);
	}
	// whereObj:查询条件
	// sortObj:排序的要求
	// skip:跳过的条数
	// limit:前几条
	async find({whereObj={},sortObj={},skip=0,limit=0}){
		await this._connect();
		return this.model.find(whereObj).sort(sortObj).skip(skip).limit(limit);
	}
	// 根据ID删除
	async deleteOneById(_id){
		await this._connect();
		return this.model.deleteOne({_id})
	}
	async updateOneById(_id,upObj){
		await this._connect();
		return this.model.updateOne({_id},upObj);
	}

}
module.exports = Db;